﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Text.RegularExpressions;

namespace ChinaLeg.Web.Lib
{
    public class Upload
    {
        ///  <summary>
        ///  判断是否是IP地址格式  0.0.0.0
        ///  </summary>
        ///  <param  name="ipAddress">待判断的IP地址</param>
        ///  <returns>true  or  false</returns>
        public static bool IsIPAddress(string ipAddress)
        {
            if (string.IsNullOrEmpty(ipAddress))
            {
                return false;
            }

            ipAddress = ipAddress.Trim();

            if (ipAddress.Length < 7 || ipAddress.Length > 15)
            {
                return false;
            }

            string regFormat = @"^(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])$";

            Regex regex = new Regex(regFormat, RegexOptions.IgnoreCase);
            return regex.IsMatch(ipAddress);
        }

        /// <summary>
        /// 获取客户端IP,默认情况下使用Request.UserHostAddress即可.
        /// 在透明代理，反向代理的情况,需要使用此方法，否则只会得到代理服务器IP       
        /// </summary>
        /// <param name="context">在HttpContext.Current还没有初始化的情况下，需要传入本参数</param>
        /// <returns>真实的客户端IP</returns>
        public static string GetClientIP(HttpContext context)
        {
            string result = String.Empty;

            result = context.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
            if (!string.IsNullOrEmpty(result))
            {
                //可能有代理  
                if (result.IndexOf(".") < -1)        //没有“.”肯定是非IPv4格式  
                {
                    result = null;
                }
                else
                {
                    if (result.IndexOf(",") > -1 || result.IndexOf(";") > -1)
                    {
                        //有“,”或";"，估计多个代理。取第一个不是内网的IP。  
                        result = result.Replace(" ", "").Replace("'", "").Replace("\"", "");
                        string[] temparyip = result.Split(",;".ToCharArray());
                        for (int i = 0; i < temparyip.Length; i++)
                        {
                            if (IsIPAddress(temparyip[i])
                                    && temparyip[i].Substring(0, 3) != "10."
                                    && temparyip[i].Substring(0, 7) != "192.168"
                                    && temparyip[i].Substring(0, 7) != "172.16.")
                            {
                                return temparyip[i];        //找到不是内网的地址  
                            }
                        }
                    }
                    else if (IsIPAddress(result))  //代理即是IP格式  
                    {
                        return result;
                    }
                    else
                    {
                        result = null;        //代理中的内容  非IP，取IP  
                    }
                }
            }

            if (string.IsNullOrEmpty(result))
            {
                result = context.Request.ServerVariables["REMOTE_ADDR"];
            }

            if (string.IsNullOrEmpty(result))
            {
                result = context.Request.UserHostAddress;
            }

            return result;
        }

        #region 传图
        /// <summary>
        /// 上传图片 
        /// </summary>
        /// <param name="upload">uploadFile</param>
        /// <param name="filepath">存储路径,类似 /upfiles/201206</param>
        public static string getPicPath(System.Web.UI.HtmlControls.HtmlInputFile upload, string filepath)
        {
            if (GetClientIP(System.Web.HttpContext.Current) != ConfigSingleton.Instance.IP)
            {
                HttpContext.Current.Response.Write("<script>alert('您所在的区域没有上传权限！');history.back()</script>");
                HttpContext.Current.Response.End();
                return "";
            }

            filepath = filepath + "/" + DateTime.Now.ToString("yyyyMM");
            string path = HttpContext.Current.Server.MapPath(filepath);
            //创建文件夹
            Utils.Common.FileHelper.CreateDirectory(path); 
            string reurl = filepath;
            string filename = DateTime.Now.ToString("yyyyMMddHHmmss") + DateTime.Now.Millisecond.ToString();
            string fileextensive = System.IO.Path.GetExtension(upload.Value);
            string ftype = upload.PostedFile.ContentType;
            if (upload.Value.Trim() != "")
            {
                if (ftype.Substring(0, 5) != "image")
                {
                    HttpContext.Current.Response.Write("<script>alert('上传图片格式不正确！');</script>");
                    //HttpContext.Current.Response.End();
                    return "";
                }
            }
            else
            {
                HttpContext.Current.Response.Write("<script>alert('请选择要上传的图片！');</script>");
                //HttpContext.Current.Response.End();
                return "";
            }
            string savepath = path + "/" + filename + fileextensive;
            reurl = reurl + "/" + filename + fileextensive;
            if (upload.PostedFile.ContentLength > 2 * 1024 * 1024)
            {
                HttpContext.Current.Response.Write("<script>alert('上传图片过大！');history.back()</script>");
                //HttpContext.Current.Response.End();
                return "";
            }
            upload.PostedFile.SaveAs(savepath);
            upload.Dispose();
            return reurl;
        }
        #endregion
    }
}